package com.elvt.bolg.web;

import cn.hutool.core.util.StrUtil;
import com.elvt.bolg.pojo.User;
import com.elvt.bolg.service.UserService;
import com.elvt.bolg.service.impl.UserServiceImpl;
import com.elvt.bolg.vo.ReturnInfo;
import org.apache.commons.io.FileUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.sql.ResultSet;

@WebServlet("/user")
@MultipartConfig
public class UserServlet extends HttpServlet {
    private UserService service=new UserServiceImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String actionName = req.getParameter("actionName");
        System.out.println(actionName+"____acacacac");

        //判断用户行为
        if ("login".equals(actionName)) {
            userLogin(req, resp);

        }else if ("logout".equals(actionName)){
            userLogout(req,resp);
        }else if ("userinfo".equals(actionName)){

            userinfo(req,resp);
        }else if ("userHead".equals(actionName)){
        //加载头像
        userHead(req,resp);
        }else if ("checkNick".equals(actionName)){
            checkNick(req,resp);
        }else if ("updateUser".equals(actionName)){

            updateUser(req,resp);
        }
    }

    /**
     * 修改用户信息！
     * @param req
     * @param resp
     */
    private void updateUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ReturnInfo resultSet=service.updateUser(req);
        req.setAttribute("resultSet",resultSet);
        req.getRequestDispatcher(req.getContextPath()+"/user/userInfo.jsp").forward(req,resp);


    }

    /**
     * 验证名称的唯一性
     * @param req
     * @param resp
     */
    private void checkNick(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String nick = req.getParameter("nick");
        System.out.println(nick+"000");
        User user= (User) req.getSession().getAttribute("user");
      Boolean flag =service.checkNick(nick,user.getUserid());
        System.out.println(flag+"ffss");
      resp.getWriter().write(flag+"");
      resp.getWriter().close();

    }

    /**
     * 加载头像
     * @param req
     * @param resp
     */
    private void userHead(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("11111111");
        //1,获取参数
        String imageName = req.getParameter("imageName");
        //2.得到图片的路径
        String realPaht=req.getServletContext().getRealPath("/WEB-INF/upload/");
        File file=new File(realPaht+"/"+imageName);
        //4，透过截取
        String pic = imageName.substring(imageName.lastIndexOf(".") + 1);
        if ("PNG".equalsIgnoreCase(pic)){
            resp.setContentType("image/png");
        }else  if ("JPG".equalsIgnoreCase(pic)){
            resp.setContentType("image/jpeg");
        }else if ("GIF".equalsIgnoreCase(pic)){

            resp.setContentType("image/gif");
        }
        //6.利用FileUtils的copy方法将图片传给浏览器
        try {
            FileUtils.copyFile(file,resp.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("输出头衔出错了");
        }

    }

    /**
     * 个人中心 用户信息
     * @param req
     * @param resp
     */
    private void userinfo(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }

    /**
     * 用户退出！
     * @param req
     * @param resp
     */
    private void userLogout(HttpServletRequest req, HttpServletResponse resp) throws IOException {
//        1.销毁session对象
        req.getSession().invalidate();
        //2.删除cookie对象
        Cookie cookie=new Cookie("user",null);
        cookie.setMaxAge(0);
        resp.addCookie(cookie);


        //3.重定向到登录页面
        resp.sendRedirect("login.jsp");

    }


    /**
     * 用户登录的方法！
     * @param req 请求
     * @param resp 相应
     */

    private void userLogin(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
         String username = req.getParameter("username");
        String password = req.getParameter("password");
        String code = req.getParameter("code");
        String loginCodeRes = (String) req.getSession().getAttribute("loginCodeRes");
        ReturnInfo returnInfo = service.queryUserByusername(username, password,code,req);

        if (returnInfo.getFlag()){
            //登录成功，把用户信息存在session中，
            User user = (User) returnInfo.getResult();
           req.getSession().setAttribute("user", user);

           //2.判断用户是否选择记住我
            String rem = req.getParameter("rem");
            if ("1".equals(rem)){
                //判断选择了记住密码，将用户信息保存到cookie中
                Cookie cookie=new Cookie("user",username+"-"+password);
                //设置失效时间
                cookie.setMaxAge(24*60*60);
                resp.addCookie(cookie);


            }else {
                Cookie cookie=new Cookie("user",null);
                //删除cookie，设置maxage为0
                cookie.setMaxAge(0);
            }
            resp.sendRedirect("index.jsp");
        }else {
            req.setAttribute("returnInfo",returnInfo);
            req.getRequestDispatcher("login.jsp").forward(req,resp);
        }
}
}
